<template>
  <div>
    <el-dialog width="400" title="授权" v-model="PowerDialogVisible" modal draggable @close="closeDialog"
      :close-on-click-modal="false">
      <el-tree ref="tree" :data="data" show-checkbox node-key="id" :default-checked-keys="defaultCheckedKeys"
        :props="defaultProps" :check-strictly="isCheck">
      </el-tree>

      <div slot="footer" class="dialog-footer">
        <el-button @click="PowerDialogVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" size="mini" @click="handleSubmit">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { queryTreeList, saveRolePermission } from '@/api/sys/role'
export default {
  name: 'PowerMenu',

  data() {
    return {
      roleId: '',
      PowerDialogVisible: false,
      defaultCheckedKeys: [],
      data: [],
      isCheck: false,
      defaultProps: {
        children: 'children',
        label: 'label',
      },
    }
  },
  mounted() { },

  methods: {
    openDialog(row) {
      this.roleId = row.roleId
      // 调用查询权限树的方法
      queryTreeList(row.roleId).then((res) => {
        // 判断请求是否成功
        if (res.data.code == 200) {
          this.getCheckedNodes(res.data.data.permissionIds)
          // 获取权限树的数据
          this.data = res.data.data.treeList
          this.defaultCheckedKeys = res.data.data.permissionIds
          // 打开对话框
          this.PowerDialogVisible = true
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 回显节点
    getCheckedNodes(ids) {
      //获取当前实例
      var that = this
      //设置延时，等待数据返回后，进行操作
      setTimeout(function () {
        //使用nextTick，等待数据返回后，进行操作
        that.$nextTick(() => {
          //定义一个空数组，用于存放节点
          const nodes = []
          //遍历权限id，获取节点
          ids.forEach((item) => {
            const node = that.$refs.tree.getNode(item)
            //判断节点是否是叶子节点，是叶子节点，则添加到数组中
            if (node.isLeaf) {
              //关键，过滤掉不是叶子节点的
              nodes.push(item)
            }
          })
          //设置选中节点
          that.$refs.tree.setCheckedKeys(nodes, true)
        })
      }, 100)
    },
    handleSubmit() {
      let params = {
        roleId: this.roleId,
        permissionIds: this.$refs.tree
          .getCheckedKeys()
          .concat(this.$refs.tree.getHalfCheckedKeys())
          .join(','),
        lastpermissionIds: this.defaultCheckedKeys.join(','),
      }
      saveRolePermission(params).then((res) => {
        if (res.status == 200) {
          this.$message.success(res.data.message)
          this.closeDialog()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    reset() {
      this.defaultCheckedKeys = []
    },
    closeDialog() {
      this.reset()
      // 关闭对话框
      this.PowerDialogVisible = false
    },
  },
}
</script>

<style lang="less" scoped></style>
